package cn.wolfcode.crm.web.filter;

import cn.wolfcode.crm.util.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFormAuthenticationFilter  extends FormAuthenticationFilter {
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.getWriter().print(new ObjectMapper().writeValueAsString(new JsonResult()));
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        String errormsg="页面出错,请联系管理员";
        if(e instanceof UnknownAccountException){
            errormsg="用户名不存在";
        }else if(e instanceof IncorrectCredentialsException){
            errormsg="密码错误";
        }
        try{
            response.getWriter().print(new ObjectMapper().writeValueAsString(new JsonResult().mark(errormsg)));
        }catch (Exception e1){
            e1.printStackTrace();
        }
        e.printStackTrace();
        return false;
    }
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
            if(isLoginRequest(request, response)){
                Subject subject = SecurityUtils.getSubject();
                if(subject != null){
                    subject.logout();
                }
            }
        return super.isAccessAllowed(request, response, mappedValue) ||
                 isPermissive(mappedValue);
    }
}
